package com.jason.weibosender.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class DownloadAgent {
	
	public interface DownloadListener{
		void onDownloadStart(long totalBytes);
		void onDownloading(long totalBytes, long currentBytes);
		void onError(long totalBytes, long currentBytes);
		void onDownloadComplete();
	}
	
	public DownloadAgent() {
	}
	public static void main(String[] args) {
		try {
			new DownloadAgent().downloadFile("http://market.nduoa.com/apk/download/431880?from=ndoo", "GET", null, null, "", new DownloadListener() {
				
				@Override
				public void onError(long totalBytes, long currentBytes) {
					System.out.println("Errrrrrrrrrrrrrrrror: " + totalBytes + " / " + currentBytes);
				}
				
				@Override
				public void onDownloadStart(long totalBytes) {
					System.out.println("SSSSSSSSSSSSSSSSSSSStart: " + totalBytes);
				}
				
				@Override
				public void onDownloadComplete() {
					System.out.println("CCCCCCCCCCCCCCCCCCCCCComplete");
				}

				@Override
				public void onDownloading(long totalBytes, long currentBytes) {
					System.out.println("DDDDDDDDDDDDDDDDDDownloading: " + totalBytes + " / " + currentBytes);
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**   
     * download file
     *    
     * @param urlString   
     * @return ��ӳ����   
     * @throws IOException   
     */    
    public byte[] downloadFile(String urlString, String method,     
            Map<String, String> parameters, Map<String, String> properties, String path, DownloadListener listener)     
            throws IOException {  
    	byte[] data = null;
        HttpURLConnection urlConnection = null;     
      
        if (method.equalsIgnoreCase("GET") && parameters != null) {     
            StringBuffer param = new StringBuffer();     
            int i = 0;     
            for (String key : parameters.keySet()) {     
                if (i == 0)     
                    param.append("?");     
                else    
                    param.append("&");     
                param.append(key).append("=").append(parameters.get(key));     
                i++;     
            }     
            urlString += param;     
        }     
        URL url = new URL(urlString);     
        HttpURLConnection.setFollowRedirects(true);
        urlConnection = (HttpURLConnection)url.openConnection();     
        urlConnection.setRequestMethod(method);     
        urlConnection.setDoOutput(false);     
        urlConnection.setDoInput(true);     
        urlConnection.setUseCaches(false);
        urlConnection.connect();
        String location = null;
        while(true){
        	location = urlConnection.getHeaderField("location");
        	if(location == null || location.length() < 1){
        		break;
        	}
        	url = new URL(location);
        	urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod(method);     
            urlConnection.setDoOutput(false);     
            urlConnection.setDoInput(true);     
            urlConnection.setUseCaches(false);
            urlConnection.connect();
        	urlConnection.connect();
        }
        
        if (properties != null)     
            for (String key : properties.keySet()) {     
                urlConnection.addRequestProperty(key, properties.get(key));     
            }     
      
        if (method.equalsIgnoreCase("POST") && parameters != null) {     
            StringBuffer param = new StringBuffer();     
            for (String key : parameters.keySet()) {     
                param.append("&");     
                param.append(key).append("=").append(parameters.get(key));     
            }     
            urlConnection.getOutputStream().write(param.toString().getBytes());     
            urlConnection.getOutputStream().flush();     
            urlConnection.getOutputStream().close();     
        }  
       int responseCode = urlConnection.getResponseCode();
       if(responseCode == HttpURLConnection.HTTP_OK){
    	   String contentLen = urlConnection.getHeaderField("content-length");
    	   long totalBytes = contentLen == null ? 0 : Integer.parseInt(contentLen);
		   if(listener != null){
			   listener.onDownloadStart(totalBytes);
		   }
    	   long currentBytes = 0;
    	   InputStream dataInput = urlConnection.getInputStream();
    	   if(dataInput.available() > 5 * 1024 * 1024){
    		   dataInput.close();
    		   return null;
    	   }
    	   byte[] dataTemp = new byte[5 * 1024 * 1024];
    	   int byteRead;
    	   try {
    		   if((byteRead = dataInput.read(dataTemp)) != -1){
    			   data = new byte[byteRead];
    			   for(int i = 0; i < data.length; i++){
    				   data[i] = dataTemp[i];
    			   }
    		   }
    		   dataInput.close();
    	   } catch (IOException e) {
    		   dataInput.close();
    		   e.printStackTrace();
			   if(listener != null){
				   listener.onError(totalBytes, currentBytes);
			   }
    	   }
    	  
       }
       return data;
    }     
}
